<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * HITI AdminCP
 *
 * @package     HITI AdminCP Project
 * @since       Monday, October 21, 2013, 6:00 PM
 * @final
 * @category    Controllers
 * @see 		Modules
 * @author      PHUOCNGUYEN - HITI Dev Team
 * @copyright   Copyright (c) 2013, HITI Corp
 */

class Modules extends CI_Controller {
	var $q = '';
	var $updated = '';
	var $failed = '';
	var $name = '';
	var $error = '';
	var $uri_arr = array();
	var $uri_str = '';

	public function __construct()
	{
		parent::__construct();
		$this->load->model('hiti_model', 'hiti', true);
		$this->hiti->load_config();
		if (check_rights() == false)
		{
			redirect();
		}
		$this->load->model($GLOBALS['var']['act'].'_model', 'Mod');
		$this->q = $this->input->get('q', true);
		$this->updated = $this->input->get('updated', true);
		$this->failed = $this->input->get('failed', true);
		$this->name = $this->input->get('name', true);
		$this->error = $this->input->get('error', true);
		$this->uri_arr = array(
			'deleted' => $GLOBALS['var']['deleted'],
			'q' => $this->q,
			'rowstart' => ''
		);
		$this->uri_str = url_uri($this->uri_arr);
	}

	public function index()
	{
		/*
		* Xu ly du lieu
		*/
		$data = array(
			'updated' => $this->updated,
			'failed' => $this->failed,
			'name' => $this->name,
			'uri_str' => $this->uri_str,
			'url_update' => site_url($GLOBALS['var']['act'].'/update'),
			'tab_modules' => array()
		);
		for ($i = 0; $i < count($GLOBALS['modules_groups']); $i++)
		{
			$rows = $this->Mod->show($i, $this->uri_arr);
			$data['tab_modules'][$i] = '';
			if ($rows) $data['tab_modules'][$i] = $rows;
		}
		/*
		* Hien thi
		*/
		$header = array(
			'title' => 'Mô đun quản lý',
			'add_link' => ($GLOBALS['cfg']['develop_mode'] ? current_url().'/update' : ''),
			'search' => true,
			'page_list' => '',
			'datetime_picker' => false,
			'submit_btn' => false,
			'cat_list' => array(),
			'uri' => $this->uri_arr,
			'act' => $GLOBALS['var']['act'],
			'do' => $GLOBALS['var']['do'],
			'id' => $GLOBALS['var']['id'],
			'filter_cat' => $GLOBALS['var']['filter_cat']
		);
		$this->load->view('header', $header);
		$this->load->view($GLOBALS['var']['act'].'/index', $data);
		$this->load->view('footer');
	}

	public function update($id = '')
	{
		/*
		* Kiem tra quyen cap nhap
		*/
		if ((!$id && !$GLOBALS['per']['add']) || ($id && !$GLOBALS['per']['edit']))
		{
			redirect($GLOBALS['var']['act']);
		}
		/*
		* Xu ly du lieu
		*/
		$this->load->helper('directory');
		$info = $this->Mod->info($id);
		$data = array(
			'info' => $info,
			'rights' => json_decode($info['rights']),
			'updated' => $this->updated,
			'name' => $this->name,
			'action' => site_url($GLOBALS['var']['act'].'/process').$this->uri_str
		);
		// Xu ly danh sach module file
		$this->db->select('file');
		if ($info['file']) $this->db->where('file !=', $info['file']);
		$query = $this->db->get('modules');
		$used_file = array();
		if ($query->num_rows() > 0)
		{
			foreach($query->result_array() as $file)
			{
				$used_file[] = $file['file'];
			}
		}
		$files = directory_map('application/controllers');
		$data['files'] = array();
		foreach ($files as $file)
		{
			if($file != 'profile.php' && $file != 'dashboard.php' && $file != 'ajax.php' && file_extension($file) == 'php')
			{
				$file = str_replace('.php', '', $file);
				if (!in_array($file, $used_file))
				{
					$data['files'][$file] = $file.'.php';
				}
			}
		}
		// Xu ly danh sach image
		$this->db->select('image');
		if ($info['image']) $this->db->where('image !=', $info['image']);
		$query = $this->db->get('modules');
		$used_image = array();
		if ($query->num_rows() > 0)
		{
			foreach($query->result_array() as $image)
			{
				$used_image[] = $image['image'];
			}
		}
		$images = directory_map('img/modules');
		$data['images'] = array();
		foreach ($images as $image)
		{
			if(file_extension($image) == 'png')
			{
				if(!in_array($image, $used_image))
				{
					$data['images'][$image] = $image;
				}
			}
		}
		/*
		* Hien thi
		*/
		$header = array(
			'title' => ($id ? 'Cập nhập' : 'Thêm mới').' mô đun',
			'add_link' => '',
			'search' => false,
			'page_list' => '',
			'datetime_picker' => false,
			'submit_btn' => true,
			'cat_list' => array(),
			'uri' => $this->uri_arr,
			'act' => $GLOBALS['var']['act'],
			'do' => $GLOBALS['var']['do'],
			'id' => $GLOBALS['var']['id'],
			'filter_cat' => $GLOBALS['var']['filter_cat']
		);
		$this->load->view('header', $header);
		$this->load->view($GLOBALS['var']['act'].'/update', $data);
		$this->load->view('footer');
	}

	public function process()
	{
		/*
		* Kiem tra POST method
		*/
		if (!$_POST)
		{
			redirect();
		}
		/*
		* Kiem tra token va tham so yeu cau
		*/
		$name_vn = $this->input->post('name_vn', true);
		if (!token_validation() || $name_vn == '')
		{
			redirect($GLOBALS['var']['act']);
		}
		/*
		* Them tham so url
		*/
		$this->uri_arr['name'] = str_replace('&', '', $name_vn);
		/*
		* Xu ly du lieu
		*/
		$id = $this->input->post('id', true);
		if ((!$id && !$GLOBALS['per']['add']) || ($id && !$GLOBALS['per']['edit']))
		{
			redirect($GLOBALS['var']['act']);
		}
		$name_en = $this->input->post('name_en', true);
		$file = $this->input->post('file', true);
		$filename = $this->input->post('filename', true);
		if (!$file)
		{
			$filename = url_title(viet_decode($filename), '_', true);
			$file = $filename;
			$filename = str_replace('.php', '', $filename);
			if ($filename)
			{
				$multiview = $this->input->post('multiview', true);
				if ($multiview)
				{
					$viewdir = APPPATH.'views/'.$filename.'/';
					@mkdir($viewdir);
					@copy(APPPATH.'views/modules/new/views/index.html', $viewdir.'/index.html');
					@copy(APPPATH.'views/modules/new/views/index.php', $viewdir.'/index.php');
					@copy(APPPATH.'views/modules/new/views/update.php', $viewdir.'/update.php');
				}
				else
				{
					$view = APPPATH.'views/'.$filename.'.php';
					if (!file_exists($view))
					{
						@copy(APPPATH.'views/modules/new/views/index.php', $view);
						$handle = fopen($view, "r");
						$contents_view = fread($handle, filesize($view));
						$contents_view = str_replace(array('Products', 'products'), array(ucwords($filename), $filename), $contents_view);
						fclose($handle);
						if (is_writable($view)) {
						    $handle = fopen($view, 'w');
						    fwrite($handle, $contents_view);
						    fclose($handle);
						}
					}
				}
				$controller = APPPATH.'controllers/'.$filename.'.php';
				if (!file_exists($controller))
				{
					@copy(APPPATH.'views/modules/new/controllers.php', $controller);
					$handle = fopen($controller, "r");
					$contents_controller = fread($handle, filesize($controller));
					$contents_controller = str_replace(array('Products', 'products'), array(ucwords($filename), $filename), $contents_controller);
					fclose($handle);
					if (is_writable($controller)) {
					    $handle = fopen($controller, 'w');
					    fwrite($handle, $contents_controller);
					    fclose($handle);
					}
				}
				$model = APPPATH.'models/'.$filename.'_model.php';
				if (!file_exists($model))
				{
					@copy(APPPATH.'views/modules/new/models.php', $model);
					$handle = fopen($model, "r");
					$contents_model = fread($handle, filesize($model));
					$contents_model = str_replace(array('Products', 'products'), array(ucwords($filename), $filename), $contents_model);
					fclose($handle);
					if (is_writable($model)) {
					    $handle = fopen($model, 'w');
					    fwrite($handle, $contents_model);
					    fclose($handle);
					}
				}
			}
		}
		$data = array(
			'name_vn' => $name_vn,
			'name_en' => $name_en ? $name_en : $name_vn,
			'image' => $this->input->post('image', true),
            'file' => $file,
            'rights' => json_encode($this->input->post('rights', true)),
            'nhom' => $this->input->post('nhom', true),
            'menu' => $this->input->post('menu', true),
            'active' => $this->input->post('active', true),
            'date_added' => date(TIME_SQL),
            'date_modified' => date(TIME_SQL)
		);
		/*
		* Ghi du lieu
		*/
		if ($this->Mod->process($data, $id))
		{
			$this->db->where('active', 1);
			$this->db->where('deleted', 0);
			$this->db->select('rights, file');
			$query = $this->db->get('modules');
			$all_right = $query->result_array();
			$user_rights = array();
			foreach ($all_right as $right) {
				$act = json_decode($right['rights']);
				if ($act->view) $user_rights[$right['file']]['view'] = '1';
				if ($act->edit) $user_rights[$right['file']]['edit'] = '1';
				if ($act->add) $user_rights[$right['file']]['add'] = '1';
				if ($act->del) $user_rights[$right['file']]['del'] = '1';
			}
			if (is_array($user_rights) && count($user_rights))
			{
				$data = array(
					'user_rights' => json_encode($user_rights)
				);
				$this->Mod->update_admin_rights($data);
				if ($GLOBALS['var']['user_id'] == 1)
				{
					$this->session->set_userdata($data);
				}
			}
			$this->uri_arr['updated'] = 1;
		}
		else
		{
			$this->uri_arr['failed'] = 1;
		}
		/*
		* Chuyen huong
		*/
		if ($id > 0)
		{
			redirect($GLOBALS['var']['act'].'/update/'.$id.url_uri($this->uri_arr));
		}
		else
		{
			redirect($GLOBALS['var']['act'].url_uri($this->uri_arr));
		}
	}
}

/* End of file modules.php */
/* Location: ./application/controllers/modules.php */